package com.ibeacon.model;

import com.ibeacon.controller.common.MessageManager;
import com.ibeacon.controller.common.WeixinUtil;

import net.sf.json.JSONObject;

/**
 * 微信获取token
 * @author winner
 *
 */
public class AccessToken {

	/**
	 * access_token
	 */

	private String token;
	
	/**
	 * jsapi_ticket
	 */
	private String ticket;
	/**
	 * 失效时间
	 */
	private Integer expiresIn;

	public String getToken() {
		if(validate()){
			return token;
		}else{
			String appid =  MessageManager.getMsg("appid");// "wxb44f389e6eaf1917";
	        String appsecret =  MessageManager.getMsg("appsecret");// "e2be14e6b1992acd730187ed85e6f1ad";
			AccessToken accessToken = WeixinUtil.getAccessToken(appid, appsecret);   
			this.token = accessToken.token;
			this.ticket = accessToken.ticket;
			this.expiresIn = accessToken.expiresIn;
			return token;
		}
	}
	
	public boolean validate(){
        String url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token="+token;
		String json = "{}";
		JSONObject jsonObj = WeixinUtil.httpRequest(url, "POST", json);
		
		if(jsonObj.containsKey("errcode")){
			return false;
		}else{
			return true;
		}
	}


	public void setToken(String token) {
		this.token = token;
	}

	public Integer getExpiresIn() {
		return expiresIn;
	}

	public void setExpiresIn(Integer expiresIn) {
		this.expiresIn = expiresIn;
	}

	public String getTicket() {
		return ticket;
	}

	public void setTicket(String ticket) {
		this.ticket = ticket;
	}
	
}
